package com.cabal.exchange.service.impl;

import com.cabal.auth.dao.CabalAuthMapper;
import com.cabal.auth.dto.CabalCharacterGmBuffDTO;
import com.cabal.auth.entity.CabalAuth;
import com.cabal.auth.entity.CabalCharacter;
import com.cabal.auth.vo.CabalAuthVo;
import com.cabal.exchange.dao.ItemExchangeMapper;
import com.cabal.exchange.entity.ItemExchange;
import com.cabal.exchange.service.ItemExchangeService;
import com.cabal.mall.service.CabalMallService;
import com.cabal.war.dao.WarMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.util.*;

@Slf4j
@Service
public class ItemExchangeServiceImpl implements ItemExchangeService {

    public static final String CABAL_STATIC_ONLINE_CODE = "CABAL_STATIC_ONLINE_CODE_";

    @Resource
    private ItemExchangeMapper itemExchangeMapper;

    @Value("${exchange-cash-number:3000}")
    private Integer exchangeCashNumber;

    @Resource
    private CabalAuthMapper cabalAuthMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CabalMallService cabalMallService;

    @Override
    public void itemExchangeJob() {

        // 清理已读邮件，避免满了
        int readCount = itemExchangeMapper.countMailReceivedAndRead();
        if(readCount > 50) {
            int clearReadCount = itemExchangeMapper.clearMailReadData();
            log.info("清理麒麟才子已读邮件{}...", clearReadCount);
        }

        // select * from Server01.dbo.cabal_mail_received_table t where t.ReceiverCharIdx = 8
        // 1、查询cabal_mail_received_table表中8角色是否有未读取的邮件
        int count = itemExchangeMapper.countMailReceived();

        if(count == 0) {
            log.info("没有需要换物品的邮件处理...");
            return;
        }

        List<ItemExchange> itemExchangeList = itemExchangeMapper.searchItemExchangeList();
        if(CollectionUtils.isEmpty(itemExchangeList)) {
            log.info("没查到需要换物品的邮件的记录...");
            return;
        }

        log.info("查到了记录需要兑换buff的记录...");
        List<ItemExchange> updateItemExchangeList = new ArrayList<>();
        for(ItemExchange itemExchange : itemExchangeList) {
            Integer itemKindIdx = itemExchange.getItemKindIdx();
            if(itemKindIdx != 1564 && itemKindIdx != 1565) {
                continue;
            }

            Integer itemOption = itemExchange.getItemOption();
            if(itemKindIdx == 1564) {
                log.info("兑换7天BUFF...");
                itemOption = 7;
            } else if(itemKindIdx == 1565) {
                itemOption = 30;
            }

            // GM DEBUFF充值
            CabalCharacterGmBuffDTO cabalCharacterGmBuffDTO = new CabalCharacterGmBuffDTO();
            cabalCharacterGmBuffDTO.setCharacterIdx(String.valueOf(itemExchange.getSenderCharIdx()));
            cabalCharacterGmBuffDTO.setDays(String.valueOf(itemOption));
            String result = cabalMallService.rechargeGmBuff(cabalCharacterGmBuffDTO);
            if("SUCCESS".equals(result)) {
                updateItemExchangeList.add(itemExchange);
            }
        }

        // 批量更新状态
        itemExchangeMapper.batchUpdateMailReceivedState(updateItemExchangeList);
    }

    @Override
    public void itemSendEveryDay() {
        // 查询所有帐号
        List<CabalAuthVo> cabalAuthVoList = cabalAuthMapper.searchAllAccountList();
        if(CollectionUtils.isEmpty(cabalAuthVoList)) {
            log.info("0点发送无帐号...");
            return;
        }

        for(CabalAuthVo cabalAuthVo : cabalAuthVoList) {
            Integer userNum = cabalAuthVo.getUserNum();
            String staticOnlineUserNumKey = CABAL_STATIC_ONLINE_CODE.concat(String.valueOf(userNum));
            String staticOnlineStaticStr = stringRedisTemplate.opsForValue().get(staticOnlineUserNumKey);
            if(StringUtils.isBlank(staticOnlineStaticStr)) {
                staticOnlineStaticStr = "0";
            }
            Integer staticOnlineTime = Integer.parseInt(staticOnlineStaticStr);
            log.info("{}玩家在线统计时间>>>>{}", userNum, staticOnlineTime);
            if(staticOnlineTime < 180) {
                continue;
            }

            log.info("{}满足条件玩家在线统计时间>>>>{}", userNum, staticOnlineTime);

            // 1、发送损坏的亡者护符副本卡
            Map<String, Object> sendItemParams = new HashMap<>();
            sendItemParams.put("itemIdx", 3394);
            sendItemParams.put("itemOpt", 2208);
            sendItemParams.put("durationIdx", 12);
            sendItemParams.put("userNum", cabalAuthVo.getUserNum());
            cabalAuthMapper.execSendItemByItemId(sendItemParams);

            // 2、VIP福利卡发送
            Integer vipLevel = cabalAuthVo.getVipLevel();
            if(vipLevel == null) {
                return;
            }

            sendItemWithVip(userNum, vipLevel);
        }

        Set<String> allKeys = stringRedisTemplate.keys(CABAL_STATIC_ONLINE_CODE + "*");
        for(String key : allKeys) {
            log.info("-----------每日物品发送清理key------------" + key);
            stringRedisTemplate.delete(key);
        }

    }

    private void sendItemWithVip(Integer userNum, Integer vipLevel) {
        for(int i = 0; i < vipLevel - 1; i++) {
            Map<String, Object> sendItemParams = new HashMap<>();
            sendItemParams.put("itemIdx", 3394);
            sendItemParams.put("itemOpt", 2208);
            sendItemParams.put("durationIdx", 31);
            sendItemParams.put("userNum", userNum);
            cabalAuthMapper.execSendItemByItemId(sendItemParams);
        }
    }

    private String getCharsetName(String dbName) {
        Charset latin1Charset = Charset.forName("ISO-8859-1");
        Charset gbkCharset = Charset.forName("GBK");

        byte[] latin1Bytes = dbName.getBytes(latin1Charset);
        String decodedText = new String(latin1Bytes, gbkCharset);
        return decodedText;
    }
}
